from django.shortcuts import render, HttpResponse
from django.forms import widgets
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


# Create your views here.
def upload(request):
    if request.method == 'POST':
        data = request.FILES.get('f1')
        with open(data.name, 'wb') as f:
            for i in data.chunks():
                f.write(i)
        return HttpResponse('ok')
    return render(request, 'index.html')


def calcc(request):
    return HttpResponse(int(request.POST.get("u1")) * int(request.POST.get("u2")))


def calc(request):
    v1 = request.GET.get("v1")
    v2 = request.GET.get("v2")
    v3 = int(v1) + int(v2)
    return HttpResponse(v3)


from django import forms


class regform(forms.Form):
    name = forms.CharField(max_length=16, label='用户名',
                           error_messages={"required": "用户名不能为空", "max_length": "用户名不能超过16位"},
                           widget=widgets.TextInput)
    real_name = forms.CharField(max_length=12, label='真实姓名',
                                error_messages={"required": "密码不能为空", "max_length": "密码不能超过12位"})
    id_num = forms.CharField(max_length=19, label='身份证号码', error_messages={"required": "身份证号码不能为空"},
                             validators=[RegexValidator(r'^[1-9]\d{16}[0-9xX]|[1-9]\d{14}$', "身份证格式不正确")])
    gender = forms.ChoiceField(label='性别', choices=((1, '男'), (2, '女'), (3, '保密')), initial=(3, "保密"))
    password = forms.CharField(min_length=6, label='密码', widget=widgets.PasswordInput(render_value=True),
                               error_messages={"required": "密码不能为空", "min_length": "密码最短为6位"})
    repwd = forms.CharField(label='确认密码', widget=widgets.PasswordInput(render_value=True),
                            error_messages={"required": "请再次输入密码"})
    email = forms.CharField(max_length=32, label='邮箱', widget=widgets.EmailInput,
                            error_messages={"required": "邮箱不能为空"})
    phone_num = forms.CharField(max_length=13, label='手机号码', error_messages={"required": "手机号码不能为空"},
                                validators=[RegexValidator(r'^1[3-9][0-9]{9}$', "手机号格式不正确")])

    def clean_name(self):
        usr_name = self.cleaned_data.get("name")
        if "傻逼" in usr_name:
            self.add_error("name", ValidationError("含有敏感词汇"))
        else:
            return usr_name

    def clean(self):
        pwd = self.cleaned_data.get('password')
        if pwd == self.cleaned_data.get('repwd'):
            return self.cleaned_data
        else:
            self.add_error("repwd", ValueError("两次密码不一致"))


def reg(request):
    reg_obj = regform()
    if request.method == 'POST':
        reg_obj = regform(request.POST)
        if reg_obj.is_valid():
            return HttpResponse('ok')
    return render(request, 'register.html', {'reg_obj': reg_obj})
